import React, { useEffect, useState } from 'react';
import ResultLayout from '../../components/result-layout';
import Multi from './multi';
import Other from './other';


const ResultPage = (props) => {
  const [resultState, setResultState] = useState([]);
  // 设置页面总风格
  const [style, setStyle] = useState('');
  const resultFromQuestions = props.location.state.current;
  console.log('当前选择是', resultFromQuestions);
  const V_value = { type: 'V', value: resultFromQuestions.V };
  const A_value = { type: 'A', value: resultFromQuestions.A };
  const R_value = { type: 'R', value: resultFromQuestions.R };
  const K_value = { type: 'K', value: resultFromQuestions.K };
  const result = [V_value, A_value, R_value, K_value];
  useEffect(() => {
    handleResult(result);
  }, []);
  useEffect(() => {}, [resultState]);
  const handleResult = (result) => {
    const resultArray = handleToPercent(
      result.sort((itemA, itemB) => itemA.value - itemB.value).reverse()
    );
    if (setMainStyle(resultArray)) {
      // true 说明有相同值
      setStyle('Multi');
    } else {
      setStyle(resultArray[0].type);
    }
    setResultState([...resultArray]);
  };
  const handleToPercent = (data) => {
    // 这里有个问题 就是数字为9会出bug 故绕了一下。
    data.forEach((item, index) => {
      item['percent'] =
        ((item.value / 16).toFixed(2) * 100).toString().substring(0, 2) + '%';
    });
    return data;
  };
  const setMainStyle = (result) => {
    let map = new Map();
    for (let i of result) {
      if (map.has(i.value)) {
        return true;
      } else {
        map.set(i.value, 1);
      }
    }
    return false;
  };
  return (
    <ResultLayout type={style}>
      {style === 'Multi' && <Multi type={style} data={resultState} />}
      {(style === 'V' || style === 'A' || style === 'R' || style === 'K') && (
        <Other type={style} style={style} data={resultState} />
      )}
    </ResultLayout>
  );
};

export default ResultPage;
